package cn.yilongquan.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.yilongquan.exception.BusinessException;
import cn.yilongquan.mapper.EmployeeMapper;
import cn.yilongquan.mapper.LoginInfoMapper;
import cn.yilongquan.mapper.MenuMapper;
import cn.yilongquan.mapper.PermissionMapper;
import cn.yilongquan.service.LoginInfoService;
import cn.yilongquan.system.RO.LoginRO;
import cn.yilongquan.system.domain.LoginInfo;
import cn.yilongquan.system.domain.Permission;
import cn.yilongquan.user.domain.Employee;
import cn.yilongquan.user.domain.Menu;
import cn.yilongquan.util.JwtUtil;
import cn.yilongquan.util.Payload;
import cn.yilongquan.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * LoginInfo业务层实现类
 * 实现基础增删改查操作
 */
@Slf4j
@Service
public class LoginInfoServiceImpl implements LoginInfoService {

    // 注入Mapper接口
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    // 注入Mapper接口
    @Autowired
    private EmployeeMapper employeeMapper;
    // 注入Mapper接口
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public LoginInfo getById(Long id) {
        // 校验ID非空
        if (id == null) {
            return null;
        }
        return loginInfoMapper.findById(id);
    }

    @Override
    public List<LoginInfo> getAll() {
        return loginInfoMapper.findAll();
    }

    @Override
    public LoginInfo getByUsername(String username) {
        // 校验用户名非空
        if (username == null || username.trim().isEmpty()) {
            return null;
        }
        return loginInfoMapper.findByUsername(username);
    }

    @Override
    public boolean save(LoginInfo loginInfo) {
        // 校验对象非空
        if (loginInfo == null) {
            return false;
        }
        // 调用Mapper插入数据，返回影响行数
        int rows = loginInfoMapper.insert(loginInfo);
        return rows > 0;
    }

    @Override
    public boolean update(LoginInfo loginInfo) {
        // 校验对象和ID非空
        if (loginInfo == null || loginInfo.getId() == null) {
            return false;
        }
        // 调用Mapper更新数据，返回影响行数
        int rows = loginInfoMapper.update(loginInfo);
        return rows > 0;
    }

    @Override
    public boolean removeById(Long id) {
        // 校验ID非空
        if (id == null) {
            return false;
        }
        // 调用Mapper删除数据，返回影响行数
        int rows = loginInfoMapper.deleteById(id);
        return rows > 0;
    }

    @Override
    public boolean removeBatch(List<Long> ids) {
        // 校验ID列表非空且不为空集合
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        // 调用Mapper批量删除，返回影响行数
        int rows = loginInfoMapper.batchDelete(ids);
        return rows > 0;
    }

    @Override
    public Long count(String username, Integer type) {
        // 调用Mapper统计记录数
        return loginInfoMapper.count(username, type);
    }

    @Override
    public R login(LoginRO loginRO) {
        //数据库是否有哦数据
        LoginInfo  loginInfo = loginInfoMapper.findByLogin(loginRO);

        if (loginInfo != null) {
            String password = loginRO.getPassword();
            String salt = loginInfo.getSalt();
            String s = SecureUtil.md5(password + salt);
            if(loginInfo.getPassword().equals(s)){
                Payload payload = new Payload();
                loginInfo.setSalt("");
                loginInfo.setPassword("");
                payload.setLogininfo(loginInfo);

                //查询菜单和权限
                Employee employee =  employeeMapper.findByLoginInfoId(loginInfo.getId());
                List<Menu> menuList =  menuMapper.findByEmployeeId(employee.getId());
                List<Long> pIds = menuList.stream().map(Menu::getParentId).collect(Collectors.toList());
                List<Menu> pMenus = menuMapper.findByIds(pIds);
                menuList.addAll(pMenus);
                System.out.println(menuList);
                //当前用户的菜单
                List<Menu> menus = findMenusByLoginInfoId(menuList);
                payload.setMenus(menus);
                System.out.println(payload);

                //查询用户的权限
                List<Permission> permissionList =  permissionMapper.findByEmployeeId(employee.getId());
                payload.setPermissions(permissionList.stream().map(Permission::getSn).collect(Collectors.toList()));

                String token = JwtUtil.generateToken(payload);
                return R.ok("登录成功：令牌：",token);
            }else{
                throw new BusinessException("用户名或者密码错误");
            }
        }

        return R.fail();
    }

    private List<Menu> findMenusByLoginInfoId(List<Menu> menuList) {

        // 2. 初始化结果集和ID映射
        List<Menu> resultMenus = new ArrayList<>();
        Map<Long, Menu> map = new HashMap<>();

        // 3. 建立ID到菜单对象的映射（方便后续查找父菜单）
        for (Menu menu : menuList) {
            map.put(menu.getId(), menu);
        }

        // 4. 构建菜单树结构（分离父菜单和子菜单）
        for (Menu menu : menuList) {
            if (menu.getParentId() == null) {
                // 无父菜单的作为根菜单
                resultMenus.add(menu);
            } else {
                // 找到父菜单并添加为子菜单
                Menu parentMenu = map.get(menu.getParentId());
                if (parentMenu != null) {
                    parentMenu.getChildren().add(menu);
                }
            }
        }

        return resultMenus;
    }
}